package com.offcn.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: wzy
 * @Date: 2021/01/25/19:48
 * @Description:
 */
@Data
public class OssTemplate {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String bucketDomain;

    /**
     * 返回上传后的文件的访问路径
     *
     * @param inputStream
     * @param fileName
     * @return
     */
    public String upload(InputStream inputStream, String fileName) {
        //1.加工文件夹和文件名
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String folderName = format.format(new Date());
        fileName = UUID.randomUUID().toString().replace("-", "") + "_" + fileName;
        //2.创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //3.上传文件流，指定bucket的结构
        ossClient.putObject(bucketName, "pic/" + folderName + "/" + fileName, inputStream);
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("上传失败!!!");
        }
        ossClient.shutdown();
        String url = "https://" + bucketName + "/pic/" + folderName + "/" + fileName;
        System.out.println("上传文件访问路径为：" + url);
        return url;


    }

}
